<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-select
          v-model="dataForm.editionId"
          placeholder="请选择出版社"
          @change="getDataList()"
        >
          <el-option
            v-for="edition in editionList"
            :key="edition.id"
            :label="edition.editionName"
            :value="edition.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="dataForm.bookClassify"
          placeholder="请选择软笔书分类"
          @change="bookTitleChange(0)"
          clearable
        >
          <el-option
            v-for="item in bookClassifyList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="dataForm.bookTitle"
          placeholder="请选择软笔书标签"
          clearable
        >
          <el-option
            v-for="item in bookTitleList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addBook(0)">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      stripe
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column prop="id" label="书id" width="180"> </el-table-column>
      <el-table-column prop="grade" label="年级" width="180"> </el-table-column>
      <el-table-column prop="border" label="顺序" width="180">
      </el-table-column>
      <el-table-column prop="name" label="软笔书封面">
        <template slot-scope="scope">
          <el-image :src="scope.row.bookCover"></el-image>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="目录类型">
        <template slot-scope="scope">
          <span v-if="scope.row.contentsType == 0">可画目录</span>
          <span v-else>固定目录</span>
        </template>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间"> </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.id, scope.row.contentsType)"
            >添加目录</el-button
          >
          <el-button type="text" size="small" @click="publishZip(scope.row.id)"
            >发布资源包</el-button
          >
          <el-button type="text" size="small" @click="addBook(1, scope.row.id)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <el-dialog
      :visible.sync="dialogBookVisible"
      :title="type == 0 ? '添加软笔书信息' : '修改软笔书信息'"
    >
      <el-form
        :rules="dataRule"
        ref="bookForm"
        :model="book"
        label-width="120px"
      >
        <el-form-item label="出版社" prop="eid">
          <el-select v-model="book.eid" placeholder="请选择出版社">
            <el-option
              v-for="edition in editionList"
              :key="edition.id"
              :label="edition.editionName"
              :value="edition.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="book.grade" />
        </el-form-item>
        <el-form-item label="顺序" prop="border">
          <el-input-number
            v-model="book.border"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="目录类型" prop="contentsType">
          <el-radio v-model="book.contentsType" :label="0" border
            >可画目录</el-radio
          >
          <el-radio v-model="book.contentsType" :label="1" border
            >固定目录</el-radio
          >
        </el-form-item>
        <el-form-item label="软笔书分类" prop="bookClassify">
          <el-select
            v-model="book.bookClassify"
            placeholder="请选择"
            @change="bookTitleChange(1)"
            clearable
          >
            <el-option
              v-for="item in bookClassifyList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="软笔书标签" prop="bookTitle">
          <el-select v-model="book.bookTitle" placeholder="请选择" clearable>
            <el-option
              v-for="item in bookTitleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="软笔书封面" prop="bookCover">
          <el-upload
            class="avatar-uploader"
            :action="'http://121.41.167.195:8000/api/oss/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="book.bookCover" :src="book.bookCover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBookVisible = false">取 消</el-button>
        <el-button
          :disabled="saveBookBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from "vue";
export default {
  data() {
    return {
      bookClassifyList: [
        {
          value: "楷书",
          label: "楷书",
        },
        {
          value: "隶书",
          label: "隶书",
        },
        {
          value: "篆书",
          label: "篆书",
        },
        {
          value: "行书",
          label: "行书",
        },
      ],
      bookTitleList: [],
      book: {
        // 课本对象
        eid: null,
        contentsType: 0,
        grade: "",
        border: 1,
        bookCover: "",
        id: null,
        bookTitle: "",
        bookClassify: "",
      },
      type: 0, // 0:添加1:修改
      dialogBookVisible: false, // 添加课本信息对话框
      saveBookBtnDisabled: false, // 课本信息保存按钮是否禁用
      dataRule: {
        // 数据规则
        grade: [{ required: true, message: "年级不能为空", trigger: "blur" }],
        eid: [{ required: true, message: "出版社不能为空", trigger: "blur" }],
        bookCover: [{ required: true, message: "封面不能为空" }],
      },
      dataForm: { editionId: "", bookClassify: "", bookTitle: "" },
      dataList: [],
      editionList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
    };
  },
  components: {},
  activated() {
    this.getEditionList();
  },
  methods: {
    // type 0.dataForm 1.book
    bookTitleChange(type) {
      var val = type == 1 ? this.book.bookClassify : this.dataForm.bookClassify;
      if (type == 1) {
        this.book.bookTitle = "";
      } else {
        this.dataForm.bookTitle = "";
      }
      if (val != "") {
        switch (val) {
          case "楷书":
            this.bookTitleList = [
              {
                value: "柳体字库",
                label: "柳体字库",
              },
              {
                value: "欧体字库",
                label: "欧体字库",
              },
              {
                value: "颜勤礼碑",
                label: "颜勤礼碑",
              },
              {
                value: "赵体字库",
                label: "赵体字库",
              },
            ];
            break;
          case "隶书":
            this.bookTitleList = [
              {
                value: "曹全碑",
                label: "曹全碑",
              },
              {
                value: "礼器碑",
                label: "礼器碑",
              },
              {
                value: "张迁碑",
                label: "张迁碑",
              },
            ];
            break;
          case "篆书":
            this.bookTitleList = [
              {
                value: "石鼓文",
                label: "石鼓文",
              },
            ];
            break;
          case "行书":
            this.bookTitleList = [
              {
                value: "大唐三藏圣教序",
                label: "大唐三藏圣教序",
              },
              {
                value: "黄州寒食贴",
                label: "黄州寒食贴",
              },
              {
                value: "兰亭序",
                label: "兰亭序",
              },
            ];
            break;
          default:
            break;
        }
      }
    },
    //上传成功后的回调函数
    handleAvatarSuccess(response) {
      this.book.bookCover = response.url;
    },
    beforeAvatarUpload() {},
    // 对话框中的保存或修改
    saveOrUpdate() {
      if (this.type == 0) {
        // 添加课本
        this.bookFormSubmit();
      } else {
        // 修改课本
        this.$refs["bookForm"].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl("/sf/cbbook/update"),
              method: "post",
              data: this.$http.adornData(this.book, false),
            }).then((response) => {
              if (response.data && response.data.code === 0) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getDataList();
                    this.dialogBookVisible = false;
                  },
                });
              } else {
                this.$message.error(response.data.msg);
              }
            });
          }
        });
      }
    },
    // 打开对话框，添加、修改
    addBook(status, id) {
      // 重置表单
      this.$nextTick(() => {
        this.$refs["bookForm"].resetFields();
      });
      if (status == 0) {
        // 添加
        this.type = 0;
        // 清空
        this.book.id = null;
        this.book.contentsType = 0;
      } else {
        // 修改
        this.type = 1;

        this.$http({
          url: this.$http.adornUrl("/sf/cbbook/info/" + id),
          method: "get",
        }).then((response) => {
          this.book = response.data.cbBook;
        });
      }
      this.dialogBookVisible = true;
    },
    // 表单提交
    bookFormSubmit() {
      // 表单验证
      this.$refs["bookForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sf/cbbook/save`),
            method: "post",
            data: this.$http.adornData(this.book, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                  this.dialogBookVisible = false;
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 发布资源包
    publishZip(id) {
      this.$confirm(`发布资源包过程可能长达5-10分钟请您耐心等待`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dataListLoading = true;
          this.$http({
            url: this.$http.adornUrl(`/sf/cbbook/createZip/${id}`),
            method: "get",
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "发布成功",
                type: "success",
                duration: 1500,
              });
            } else {
              this.$message.error(data.msg);
            }
            this.dataListLoading = false;
          });
        })
        .catch(() => {});
    },
    getEditionList() {
      this.$http({
        url: this.$http.adornUrl("/sf/cbbookedition/getEditionList"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.editionList = data.editionList;

          if (this.editionList.length != 0) {
            this.dataForm.editionId = this.editionList[0].id;
          }
          var eid = this.$cookie.get("eid");
          if (eid != null && eid != "") {
            this.dataForm.editionId = eid;
          }
          this.getDataList();
        } else {
          this.editionList = [];
        }
      });
    },
    // 获取校区分页数据
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sf/cbbook/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          editionId: this.dataForm.editionId,
          bookClassify: this.dataForm.bookClassify,
          bookTitle: this.dataForm.bookTitle,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.dataList = data.bookPage.records;
          this.totalPage = data.bookPage.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 新增或修改
    addOrUpdateHandle(bookId, contentsType) {
      this.$cookie.set("eid", this.dataForm.editionId);
      if (contentsType == 0) {
        // 可画目录
        this.$router.push({
          path: "/ruanbi/ruanbiContentAdd/" + bookId,
        });
      } else {
        // 固定目录
        this.$router.push({
          path: "/ruanbi/ruanbiContentAdd2/" + bookId,
        });
      }
    },
    // 删除
    deleteHandle(id) {
      this.$confirm(`确定对[软笔书id=${id}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbbook/delete"),
            method: "post",
            data: this.$http.adornData([id], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>